package com.jf.cloud.service.sysmanager.support.connect;


import java.util.Map;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.springframework.util.Assert;

public class HttpClientHandle {
	private static Logger log = Logger.getLogger(HttpClientHandle.class);
	
	public HttpClientHandle() {
		Logger.getLogger("org.apache.commons.httpclient").setLevel(Level.INFO);
		Logger.getLogger("httpclient.wire.header").setLevel(Level.INFO); 
		Logger.getLogger("httpclient.wire.content").setLevel(Level.INFO); 
	}
	
	public PostMethod getPostMethod(String url) {
		PostMethod postMethod = new UTF8PostMethod(url);
		return postMethod;
	}

	public PostMethod getPostMethod(String url, String charset) {
		com.jf.cloud.service.sysmanager.support.connect.PostMethod postMethod = new com.jf.cloud.service.sysmanager.support.connect.PostMethod(url);
		postMethod.setCharset(charset);
		return postMethod;
	}

	public PostMethod setPostMethodValue(String parametername, String parameternamevalue, PostMethod postMethod) {
		try {
			if (!"".equals(parametername)) {
				postMethod.addParameter(parametername, parameternamevalue);
			}
		} catch (Exception ex) {
			log.error("error existed in set PostMethodValue", ex);
		}
		return postMethod;
	}

	public PostMethod setPostMethodValue(NameValuePair[] nvp, PostMethod postMethod) {
		if (nvp != null && nvp.length > 0) {
			postMethod.setRequestBody(nvp);
		}
		return postMethod;
	}

	/**
	 * ��������
	 * @param postMethod
	 * @return
	 */
	public String doPostURL(PostMethod postMethod) {
		String countback = "";
		HttpClient httpClient = new HttpClient(ConnectionManager.manager);
		httpClient.getHttpConnectionManager().getParams().setSoTimeout(10 * 1000); // 10sδ��ȡ������ �������ʶ���Ϊ��ʱ
		httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(10 * 1000); // 10sδ�ҵ�Ŀ��url���� ���ӳ�ʱʱ��
		int statusCode = 0;
		try {
			log.info("���������������ÿ�ʼ.......���ʵ�ַ��" + postMethod.getURI().getEscapedPath());
			postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
			statusCode = httpClient.executeMethod(postMethod);
			if (statusCode != HttpStatus.SC_OK) {
				log.error("�������������return status is not right :" + statusCode);
				if (statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
					Header header = postMethod.getResponseHeader("location");
					log.error("���������������תURL:" + header.getValue());
				}
				log.error("������������ﷵ��ֵΪ :" + postMethod.getResponseBodyAsString());
				return countback;
			}
			// ��ȡ����
			countback = postMethod.getResponseBodyAsString();
		} catch (Exception e) {
			try {
				log.error("������������﷢���������,�����ַ����" + postMethod.getURI().toString() + "��", e);
			} catch (Exception e1) {
				log.error("�������������postMethod.getURI()������", e1);
			}
			// �����������쳣��������Э�鲻�Ի��߷��ص�����������
			return countback;
		} finally {
			try {
				postMethod.releaseConnection();
				httpClient = null;
			} catch (Exception e) {
				log.error("�޷��ر����Ӵ���", e);
			}
		}
		log.info("���������������óɹ����.......");
		log.debug("���������������óɹ����.......����ֵ��" + countback);
		return countback;
	}
	
	/**
	 * ʹ�÷���һ�����󣬲����ؽ��----------------------------
	 * Ĭ���Ƿ���Utf8 ����
	 * �����ַ�����Ҳ֧��------------------------------------
	 */
	public String post(Param param){
		String rs = "";
		Assert.notNull(param);
		Assert.hasText(param.getUrl());
		PostMethod postMethod = null;
		if(param.getEncoding()==null || param.getEncoding().equals("") || param.getEncoding().equals(Encoding.UTF8)){
			postMethod = this.getPostMethod(param.getUrl().trim());
		}else {
			postMethod = this.getPostMethod(param.getUrl(), param.getEncoding());
		}
		Map<String, String> pMap = param.getParams();
		if(pMap!=null && !pMap.isEmpty()){
			for (Map.Entry<String, String> e : pMap.entrySet()) {
				this.setPostMethodValue(e.getKey(), e.getValue(), postMethod) ;
			}
		}
		rs = this.doPostURL(postMethod);
		return rs;
	}
}
